package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author 孤风雪影
 * @date 2021/2/19 0:26
 */

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:"; //+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1.扫描最近三天需要参与秒杀的活动
        R latest3DaysSession = this.couponFeignService.getLatest3DaysSession();
        if (latest3DaysSession.getCode() == 0) {
            //上架商品
            List<SeckillSessionsWithSkus> sessions = latest3DaysSession.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存到redis
            //1.缓存活动信息
            this.saveSessionInfos(sessions);
            //2.缓存活动的商品信息
            this.saveSessionSkuInfos(sessions);
        }
    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException e) {
        log.error("getCurrentSeckillSkusResource被限流了...");
        return null;
    }

    /**
     * 获取当前参与秒杀的skus
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource", blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1.确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();

        try (Entry entry = SphU.entry("seckillSkus")) {
            //查询所有的秒杀场次keys
            Set<String> keys = this.stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            if (!CollectionUtils.isEmpty(keys)) {
                for (String key : keys) {
                    String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                    String[] s = replace.split("_");
                    long start = Long.parseLong(s[0]);
                    long end = Long.parseLong(s[1]);
                    if (time >= start && time <= end) {
                        //2.获取这个秒杀场次需要的所有商品信息
                        List<String> range = this.stringRedisTemplate.opsForList().range(key, -100, 100);
                        BoundHashOperations<String, String, String> hashOps = this.stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                        List<String> list = hashOps.multiGet(range);
                        if (!CollectionUtils.isEmpty(list)) {
                            List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                                SeckillSkuRedisTo redisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                                return redisTo;
                            }).collect(Collectors.toList());
                            return collect;
                        }
                        break;
                    }
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流,{}", e.getMessage());
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //1.找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = this.stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (!CollectionUtils.isEmpty(keys)) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String jsonString = hashOps.get(key);
                    SeckillSkuRedisTo skuRedisTo = JSON.parseObject(jsonString, SeckillSkuRedisTo.class);

                    //是否返回随机码
                    long current = new Date().getTime();
                    if (current >= skuRedisTo.getStartTime() && current <= skuRedisTo.getEndTime()) {

                    } else {
                        skuRedisTo.setRandomCode(null);
                    }

                    return skuRedisTo;
                }
            }
        }

        return null;
    }


    /**
     * TODO 上架秒杀商品的时候,每一个数据都有过期时间
     * TODO 秒杀后续的流程,收货地址
     * @param killId 1_48
     * @param key 随机码
     * @param num 2
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = this.stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String jsonString = hashOps.get(killId);
        if (!StringUtils.isEmpty(jsonString)) {
            SeckillSkuRedisTo skuRedisTo = JSON.parseObject(jsonString, SeckillSkuRedisTo.class);
            //校验合法性
            Long startTime = skuRedisTo.getStartTime();
            Long endTime = skuRedisTo.getEndTime();
            long currentTime = new Date().getTime();
            long ttl = endTime - startTime;

            //1.检验时间的合法性
            if (currentTime >= startTime && currentTime <= endTime) {
                //2.校验随机码和商品id
                String randomCode = skuRedisTo.getRandomCode();
                String redisID = skuRedisTo.getPromotionSessionId() + "_" + skuRedisTo.getSkuId();
                if (randomCode.equals(key) && redisID.equals(killId)) {
                    //3.验证购物数量是否合理
                    if (num <= skuRedisTo.getSeckillLimit()) {
                        //4.验证这个人是否已经购买过,幂等性
                        String redisKey = memberRespVo.getId() + "_" + redisID;
                        //自动过期
                        Boolean aBoolean = this.stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功说明从来没有买过
                            RSemaphore semaphore = this.redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean tryAcquire = semaphore.tryAcquire(num);
                            if (tryAcquire) {
                                //秒杀成功;
                                //快速下单
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(memberRespVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(skuRedisTo.getPromotionSessionId());
                                orderTo.setSkuId(skuRedisTo.getSkuId());
                                orderTo.setSeckillPrice(skuRedisTo.getSeckillPrice());
                                this.rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                long s2 = System.currentTimeMillis();
                                log.info("耗时...{}", (s2 - s1));
                                return timeId;
                            }
                        }
                    }
                }
            }
        }

        return null;
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions) {
        if (!CollectionUtils.isEmpty(sessions)) {
            sessions.forEach(session -> {
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                String key = this.SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
                Boolean hasKey = stringRedisTemplate.hasKey(key);
                //缓存活动信息
                if (!hasKey) {
                    List<String> collect = session.getSeckillSkuRelationEntities().stream().map(
                            seckillSkuVo -> seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString()).collect(Collectors.toList());
                    this.stringRedisTemplate.opsForList().leftPushAll(key, collect);
                }
            });
        }
    }

    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions) {
        if (!CollectionUtils.isEmpty(sessions)) {
            sessions.forEach(session -> {
                //准备hash操作
                BoundHashOperations<String, Object, Object> ops = this.stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                session.getSeckillSkuRelationEntities().forEach(seckillSkuVo -> {

                    if (!ops.hasKey(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString())) {
                        //缓存商品
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        //1.sku的基本数据
                        R r = this.productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                        if (r.getCode() == 0) {
                            SkuInfoVo skuInfo = r.getDataByKey("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfo(skuInfo);
                        }

                        //2.sku秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo, redisTo);

                        //3.设置当前商品的秒杀时间信息
                        redisTo.setStartTime(session.getStartTime().getTime());
                        redisTo.setEndTime(session.getEndTime().getTime());

                        //4.设置随机码
                        String token = UUID.randomUUID().toString().replace("-", "");
                        redisTo.setRandomCode(token);

                        String jsonString = JSON.toJSONString(redisTo);
                        ops.put(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString(), jsonString);

                        //5.使用库存作为分布式的信号量 限流
                        RSemaphore semaphore = redissonClient.getSemaphore(this.SKU_STOCK_SEMAPHORE + token);
                        //商品可以秒杀的数量作为信号量
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                    }

                });
            });
        }
    }
}
